package com.example.httpmessageconverter.config;

import com.example.httpmessageconverter.entity.DemoObj;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.Nullable;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class MyMessageConverter extends AbstractHttpMessageConverter<DemoObj> {
    public MyMessageConverter(){
        //设置我们新定义的媒体类型为application/x-wisely
//        super(new MediaType("application","x-wisely", Charset.forName("UTF-8")));
//        super(StandardCharsets.ISO_8859_1, MediaType.TEXT_PLAIN, MediaType.ALL);
        super(StandardCharsets.ISO_8859_1, MediaType.TEXT_PLAIN);
    }
    //标明本HttpMessageConverter只处理DemoObj这个类
    @Override
    protected boolean supports(Class<?> aClass) {
        return DemoObj.class.isAssignableFrom(aClass);
    }

    @Override
    public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
        return false;
    }

    //把中间用-隔开的数据转成DemoObj对象
    @Override
    protected DemoObj readInternal(Class<? extends DemoObj> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        String temp= StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8"));
        String[] tempArr=temp.split("-");
        return new DemoObj(new Long(tempArr[0]), tempArr[1]);
    }

    //把DemoObj对象转化成字符串并输出到response中
    @Override
    protected void writeInternal(DemoObj obj, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        String out="hello:"+obj.getId()+"-"+obj.getName();
        httpOutputMessage.getBody().write(out.getBytes());
    }
}